package com.zw.controller.user;

import com.zw.annotation.Anonymous;
import com.zw.constant.Constants;
import com.zw.core.domain.AjaxResult;
import com.zw.core.domain.model.LoginUser;
import com.zw.dto.UserForgotDto;
import com.zw.dto.UserLoginDto;
import com.zw.dto.UserRegisterDto;
import com.zw.manager.AsyncManager;
import com.zw.manager.factory.AsyncFactory;
import com.zw.service.UserService;
import com.zw.utils.MessageUtils;
import com.zw.utils.StringUtils;
import com.zw.web.service.TokenService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 用户
 */
@Tag(name = "用户")
@RestController("userController")
@RequestMapping("/user/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;

    /**
     * 用户注册
     *
     * @param userRegisterDto
     * @return
     */
    @Anonymous
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserRegisterDto userRegisterDto) {
        log.info("用户注册:{}", userRegisterDto);
        return userService.register(userRegisterDto) ? AjaxResult.success() : AjaxResult.error("注册失败");
    }

    /**
     * 激活用户
     *
     * @param username
     * @param email
     * @return
     */
    @Anonymous
    @Operation(summary = "用户激活")
    @GetMapping("/activate")
    public ModelAndView activate(@RequestParam("username") String username, @RequestParam("email") String email) {
        // 获取当前时间用于显示
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String activationTime = now.format(formatter);

        // 尝试激活用户
        boolean activationResult = userService.activate(username, email);

        // 设置模型属性
        ModelAndView modelAndView = new ModelAndView("activate_status");

        modelAndView.addObject("username", username);
        modelAndView.addObject("email", email);
        modelAndView.addObject("activationTime", activationTime);

        // 根据激活结果设置状态和错误信息
        if (activationResult) {
            modelAndView.addObject("status", "success");
        } else {
            modelAndView.addObject("status", "error");
            modelAndView.addObject("errorCode", "ACT-" + now.getMinute() + now.getSecond());
            modelAndView.addObject("errorMessage", "激活失败，请检查链接或联系客服");
        }
        return modelAndView;
    }

    /**
     * 用户登录
     *
     * @param userLoginDto
     * @return
     */
    @Anonymous
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserLoginDto userLoginDto) {
        return AjaxResult.success(userService.login(userLoginDto));
    }


    /**
     * 重置密码
     *
     * @param userForgotDto
     * @return
     */
    @Anonymous
    @Operation(summary = "重置密码")
    @PostMapping("/forgot")
    public AjaxResult forgot(@RequestBody UserForgotDto userForgotDto) {
        return userService.forgot(userForgotDto) ? AjaxResult.success() : AjaxResult.error("重置密码失败");
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @Anonymous
    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        return AjaxResult.success(MessageUtils.message("user.logout.success"));
    }


    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @Anonymous
    @Operation(summary = "发送验证码")
    @GetMapping("/sendCode")
    public AjaxResult sendCode(@RequestParam("email") String email) {
        return userService.sendCode(email) ? AjaxResult.success() : AjaxResult.error("发送验证码失败");
    }

    /**
     * 用户信息
     *
     * @return
     */
    @Operation(summary = "用户信息")
    @GetMapping("/info")
    @PreAuthorize("@ss.authenticated()")
    public AjaxResult info() {
        return AjaxResult.success(userService.getUserInfo());
    }

}
